
public class ACRReader {

	private PcscReader pcscReader;
	private CardSelector acr;
	
	/**
	 * 初始化
	 * @return
	 */
	public String init(){
		String[] readerList = null;
		try{
			pcscReader = new PcscReader();
			pcscReader = new PcscReader();
			pcscReader.setPollingEventHandler(new PollingEvent());
			acr = new CardSelector(pcscReader);
			pcscReader.setEventHandler(new ReaderEvents());
			readerList = pcscReader.listTerminals();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		StringBuilder device = new StringBuilder();
		if(readerList!=null){
			for(String s : readerList){
				device.append(s);
			}
		}
		return device.toString();
	}
	/**
	 * 连接
	 * @param device
	 * @return
	 */
	public boolean connect(String device){
		try{
			if(pcscReader._connectionActive){
				close();
			}
			pcscReader.connect(device, "*");
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 调用 get data 接口
	 * @param cmd
	 * @return
	 */
	public String getData(String cmd){
		cmd = cmd.replaceAll(" ", "");
		byte[] buff = new byte[cmd.length() / 2];
		int b = 0;
		for (int i = 0; i < cmd.length(); i = i + 2) {
			buff[b] = (byte) ((Integer) Integer.parseInt(
					cmd.substring(i, i + 2), 16)).byteValue();
			b++;
		}
		try {
			return acr.Controlapdu(buff, 3500);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}
	/**
	 * 断开读卡器
	 */
	public void close(){
		try {
			pcscReader.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获得序列号
	 * @return
	 */
	public static String getSerialNumber(){
		String serial_number = null;
		ACRReader reader = new ACRReader();
		String device = reader.init();
		if(device == null){
			return null;
		}
		if(!reader.connect(device)){
			return null;
		}
		serial_number = reader.getData("FF CA 00 00 00");
		if(serial_number!=null){
			serial_number = serial_number.trim();
			String[] arr = serial_number.split(" ");
			StringBuilder sn = new StringBuilder();
			for(int i=0;i<4;i++){
				sn.append(arr[i]);
			}
			return sn.toString();
		}
		return serial_number;
	}
	
	//FF CA 00 00 00
	public static void main(String[] args) {
		System.out.println(getSerialNumber());
	}

}
